/**
 * desc：
 * author：王文军
 * date：  2021/10/27 21:12
 */
const fse = require('fs-extra')
const inquirer = require('inquirer')
const glob = require("glob");
const ejs = require("ejs");

async function install(options) {
  const projectPrompt = [];
  const descriptionPrompt = {
    type: "input",
    name: "description",
    message: "请输入项目描述信息",
    default: "",
    validate: function (v) {
      // 对输入的内容进行校验，返回false则表示输入无效
      const done = this.async();
      setTimeout(function () {
        if (!v) {
          done("请输入合法的项目描述！");
          return;
        }
        done(null, true);
      }, 0);
    },
  };
  projectPrompt.push(descriptionPrompt);
  //5.2 获取组件信息
  const projectInfo = await inquirer.prompt(projectPrompt);
  options.projectInfo.description = projectInfo.description
  try {
    const {sourcePath, targetPath} = options; // 当前目录
    fse.ensureDirSync(sourcePath); // 如果缓存的目录不存在就自己创建
    fse.ensureDirSync(targetPath); // 如果缓存的目录不存在就自己创建
    fse.copySync(sourcePath, targetPath); // 拷贝模版代码
    const templateIgnore = options.templateInfo.ignore || [];
    const ignore = ["**/node_modules/**", ...templateIgnore];
    console.warn("templateInfo", options);
    await ejsRender({ ignore,targetPath,data:options.projectInfo });
  } catch (e) {
    throw e;
  } finally {
  }
  // const { installCommand, startCommand } = this.templateInfo;
  // // 依赖安装
  // await this.execCommand(installCommand, "模版依赖过程安装失败！");
  // // 启动命令执行
  // await this.execCommand(startCommand, "模版项目启动失败！");
}

// ejs渲染
async function ejsRender(options) {
  const dir = options.targetPath;
  const projectInfo = options.data;
  return new Promise((resolve, reject) => {
    glob(
      "**",
      {
        cwd: dir,
        ignore: options.ignore || "",
        nodir: true,
      },
      (err, files) => {
        if (err) {
          reject(err);
        }
        Promise.all(
          files.map((file) => {
            const filePath = path.resolve(dir, file);
            return new Promise((resolve1, reject1) => {
              ejs.renderFile(filePath, projectInfo, {}, (err, result) => {
                if (err) {
                  reject1(err);
                } else {
                  fse.writeFileSync(filePath, result);
                  resolve(result);
                }
              });
            });
          })
        )
          .then(() => {
            resolve();
          })
          .catch((err) => {
            reject(err);
          });
      }
    );
  });
}

module.exports = install
